package com.hbnu.mysql;

import com.mysql.cj.jdbc.Driver;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

import static java.sql.DriverManager.*;


//数据库连接和添加数据
public class DatabaseDemo1 {
    public static void main(String[] args) {
        Connection connection = null;
        Statement statement = null;
        try {
            registerDriver(new Driver());

            //连接数据库
            String url = "jdbc:mysql://localhost:3306/class2211?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC&characterEncoding=utf-8";       //一定要设置时间时区，否则会报错
                                                                                                                                                            //是否要服务器认证，设为否
                                                                                                                                                            //这里改了编码，要记得，后面编码格式报错了可以回来排查
                                                                                                                                                            //?前面的好改，其他的再说
            String user = "root";
            String password = "12123";
            connection = getConnection(url,user,password);

            System.out.println(connection);

            //获取数据库操作对象
            statement = connection.createStatement();

            //执行SQL语句
            String sql = "insert into nncc1(c1,c2,c3) values('John','34','UK')";
            int row = statement.executeUpdate(sql);
            System.out.println("影响了数据库"+row+"条数据");





        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        finally {
            try {
                if (statement != null){
                    statement.close();
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
            try {
                if (connection != null){
                    connection.close();
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }

}
